package src;

import java.io.IOException;

import lib.ArgumentValidator;
import lib.messaging.NetworkAddress;
import lib.rpc.IRPCMethods;

public class ClientCommandHandler implements IClientCommandHandler
{
    private NetworkAddress clientAddress;
    private IRPCMethods clientRPCMethods;
    private String userFileSuffix;

    public ClientCommandHandler(
            NetworkAddress clientAddress,
            IRPCMethods clientRPCMethods,
            String userFileSuffix)
    {
        ArgumentValidator.IsNotNull("clientAddress", clientAddress);
        ArgumentValidator.IsNotNull("clientRPCMethods", clientRPCMethods);
        ArgumentValidator.IsNotNullOrEmpty("userFileSuffix", userFileSuffix);

        this.clientAddress = clientAddress;
        this.clientRPCMethods = clientRPCMethods;
        this.userFileSuffix = userFileSuffix;
    }

    @Override
    public void HandleCreateUserCommand(NetworkAddress serverAddress, int roundID, String userName)
            throws ClassNotFoundException, IOException
    {
        String fileName = userName + userFileSuffix;
        clientRPCMethods.CreateFile(clientAddress, serverAddress, roundID, fileName);
    }

    @Override
    public String HandleFetchCommand(NetworkAddress serverAddress,  int roundID, String userName, int postNumber)
            throws ClassNotFoundException, IOException
    {
        String fileName = userName + userFileSuffix;

        String msg = clientRPCMethods.GetLineFromFile(
                clientAddress,
                serverAddress,
                roundID,
                fileName,
                postNumber);

        return msg;
    }

    @Override
    public void HandleUpdateCommand(NetworkAddress serverAddress, int roundID, String userName, String data)
            throws ClassNotFoundException, IOException
    {
        String fileName = userName + userFileSuffix;

        clientRPCMethods.AppendLineToFile(
                clientAddress,
                serverAddress,
                roundID,
                fileName,
                data);
    }
}
